package demo.web;

import demo.entity.SysUser;
import demo.exception.IncorrectCredentialsException;
import demo.service.UserService;
import demo.service.impl.UserServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.annotation.Action;
import org.smart4j.framework.annotation.Controller;
import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.bean.Param;
import org.smart4j.framework.bean.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by Wenxin on 2017/3/13.
 */
@Controller
public class UserController {

    private static Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Inject
    private UserServiceImpl userService;

    @Action("post:/user/login")
    public View loginSubmit(Param param, HttpSession session) {
        Map<String, Object> map = param.getMap();
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        LOGGER.debug("{} attempt to login", username);
        if (username == null || password == null) {
            return new View("user/login.jsp");
        }
        try {
            SysUser sysUser = userService.login(username, password);
            session.setAttribute("activedUser", sysUser);
            return new View("/user/loginSuccess");
        } catch (Exception e) {
            LOGGER.debug("login failure", e);
            return new View("user/login.jsp");
        }
    }

    @Action("get:/user/list")
    public View userList(HttpServletRequest request) {
        List<SysUser> sysUsers = userService.queryList(0, 100);
        request.setAttribute("userList", sysUsers);
        return new View("user/list.jsp");
    }

    @Action("post:/user/login")
    public View add() {
        return new View("user/login.jsp");
    }

    @Action("get:/user/login")
    public View delete() {
        return new View("user/login.jsp");
    }

    @Action("get:/user/update")
    public View updatePage(Param param, HttpServletRequest request) {
        Long id = param.getLong("id");
        SysUser sysUser = userService.query(id);
        request.setAttribute("user", sysUser);
        return new View("user/update.jsp");
    }

    @Action("post:/user/update")
    public View updateSubmit(Param param, HttpServletRequest request) {
        Long id = param.getLong("id");
        SysUser sysUser = userService.query(id);
        String oldPassword = param.getString("oldPassword").trim();
        String newPassword = param.getString("newPassword").trim();
        if (StringUtils.isNotEmpty(oldPassword) && StringUtils.isNotEmpty(newPassword)) {
            boolean success = false;
            try {
                success = userService.updatePassword(id, newPassword, oldPassword);
            } catch (IncorrectCredentialsException e) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("add user failure");
                request.setAttribute("errorInfo", "旧密码错误");
            }
            if (success) {
                return new View("/user/login");
            } else {
                String errorInfo = (String) request.getAttribute("errorInfo");
                if (StringUtils.isEmpty(errorInfo))
                    request.setAttribute("errorInfo", "修改失败！");
                return new View("user/update.jsp");
            }
        }
        return new View("user/login.jsp");
    }

    @Action("get:/user/delete")
    public View deleteSubmit(Param param) {
        long id = param.getLong("id");
        userService.delete(id);
        return new View("/user/list");
    }

    @Action("get:/user/add")
    public View addPage(Param param) {
        return new View("user/add.jsp");
    }

    @Action("post:/user/add")
    public View addSubmit(Param param, HttpServletRequest request) {
        String username = param.getString("username");
        String password = param.getString("password");
        boolean success = false;
        try {
            success = userService.addUser(new SysUser(username, password));
        } catch (IncorrectCredentialsException e) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("add user failure");
            request.setAttribute("errorInfo", "旧密码错误");
        }
        if (success) {
            return new View("/user/list");
        } else {

            request.setAttribute("errorInfo", "添加用户失败！");
            return new View("user/add.jsp");
        }
    }

    @Action("get:/user/loginSuccess")
    public View successPage(Param param) {
        return new View("user/success.jsp");
    }


}
